//
//  FKDownloadConfig.m
//  FK
//
//  Created by 江山 王 on 6/9/12.
//  Copyright (c) 2012 Finalist. All rights reserved.
//

#import "FKDownloadConfig.h"

@interface FKDownloadConfig()

/**
 * 当前应用程序的documents目录
 *
 * 目录结构: <Application_Home>/Documents/
 * 
 */
+ (NSString *)appDocumentsDir;

/**
 * 当前应用程序的临时目录
 *
 * Structure: <Application_Home>/tmp/
 */
+ (NSString *)appTemporaryDir;

/**
 * 当前应用程序的caches目录
 *
 * 目录结构: <Application_Home>/Library/Caches/
 * 
 */
+ (NSString *)appCachesDir;

/**
 * 如果指定目录在当前应用的目录结构中存在则返回存在的目录路径
 * 如果不存在指根据指定的目录路径创建目录
 */
+ (NSString *)createOrGetDirWithName:(NSString *)dirPathName;

@end


@implementation FKDownloadConfig

#pragma mark - Public methods implementation

+ (NSString *)temporaryFileDownloadPath {
    NSString *_path = [[[self class] appTemporaryDir] stringByAppendingPathComponent:FKString("tempdownloads")];
    return [[self class] createOrGetDirWithName:_path];
}

+ (NSString *)temporaryUncompressedDataDownloadPath {
    NSString *_path = [[[self class] appDocumentsDir] stringByAppendingPathComponent:FKString("tempUncompressedDownloads")];
    return [[self class] createOrGetDirWithName:_path];
}

+ (NSString *)downloadDestinationPath {
    NSString *_path = [[[self class] appDocumentsDir] stringByAppendingPathComponent:FKString("downloads")];
    return [[self class] createOrGetDirWithName:_path];
}

#pragma mark - Private methods implementation

/**
 * 当前应用程序的documents目录
 *
 * 目录结构: <Application_Home>/Documents/
 * 
 */
+ (NSString *)appDocumentsDir {
	
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	
	return [paths objectAtIndex:0];
}

/**
 * 当前应用程序的临时目录
 *
 * Structure: <Application_Home>/tmp/
 */
+ (NSString *)appTemporaryDir {
	return NSTemporaryDirectory();
}

/**
 * 当前应用程序的caches目录
 *
 * 目录结构: <Application_Home>/Library/Caches/
 * 
 */
+ (NSString *)appCachesDir {
	
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
	
	return [paths objectAtIndex:0];
    
}

/**
 * 如果指定目录在当前应用的目录结构中存在则返回存在的目录路径
 * 如果不存在指根据指定的目录路径创建目录
 */
+ (NSString *)createOrGetDirWithName:(NSString *)dirPathName {
	
	NSFileManager *fileManager = [NSFileManager defaultManager];
	NSError *error = nil;
	
	if (![fileManager fileExistsAtPath:dirPathName]) {
		if(![fileManager createDirectoryAtPath:dirPathName withIntermediateDirectories:YES attributes:nil error:&error]) {
			NSLog(@"ERROR: Failed to create dir path %@ with comming message %@ .", dirPathName,[error localizedDescription]);
		}
	}
	return	dirPathName;
}

@end